package com.example.springbootlogin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.springbootlogin.domain.User;
import com.example.springbootlogin.repository.UserDao;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    @Resource
    private UserDao userDao;

    /**
     * 生成token
     * @param userId 用户ID
     * @param password 用户密码
     * @return token字符串
     */
    public String genToken(Long userId, String password) {
        // 设置过期时间为2小时
        Date expireDate = new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000);
        
        // 使用用户密码作为密钥
        return JWT.create()
                .withAudience(userId.toString()) // 将userId存储在token中
                .withExpiresAt(expireDate) // 设置过期时间
                .sign(Algorithm.HMAC256(password)); // 使用用户密码作为密钥
    }

    /**
     * 从请求头中获取当前登录用户
     * @return 当前登录用户
     */
    public User getCurrentUser() {
        // 从请求头中获取token
        String token = getRequest().getHeader("token");
        if (token == null || token.isEmpty()) {
            return null;
        }
        
        // 解析token获取用户ID
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (Exception e) {
            return null;
        }
        
        // 根据用户ID查询用户信息
        return userDao.findById(Long.valueOf(userId)).orElse(null);
    }

    /**
     * 验证token是否有效
     * @param token token字符串
     * @param user 用户对象
     * @return 是否有效
     */
    public boolean verify(String token, User user) {
        try {
            // 使用用户密码作为密钥创建验证器
            Algorithm algorithm = Algorithm.HMAC256(user.getPassword());
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 验证token
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 获取当前请求对象
     * @return HttpServletRequest
     */
    private HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }
}